package com.cwx.mychat.config;

import com.cwx.mychat.entity.constant.CodeConstant;
import com.cwx.mychat.entity.constant.SysSettingConstant;
import com.cwx.mychat.entity.dto.TokenUserInfoDto;
import com.cwx.mychat.utils.common.CommonUtil;
import com.cwx.mychat.utils.redis.RedisComponent;
import com.cwx.mychat.utils.redis.RedisUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component("appConfig")
@Data
@Slf4j
public class AppConfig {

    /**
     * websocket 端口
     */
    @Value("${ws.port:}")
    private Integer wsPort;

    @Value("${ws.path}")
    private String wsPath;
    /**
     * 是否管理员
     */
    @Value("${admin.emails:}")
    private String adminEmail;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisComponent redisComponent;

    @Autowired
    private Environment environment;

    /**
     * 初始化应用程序
     */
    @PostConstruct
    public void init(){
        log.info("初始化应用程序...");
        //获取当前环境
        String[] activeProfile = environment.getActiveProfiles();
        log.info("当前环境配置: " + String.join(", ", activeProfile));
        //将基础配置上传到redis中
       try{
           SysSettingConstant sysSettingConstant = new SysSettingConstant();
           boolean set = redisUtil.set(CodeConstant.REDIS_KEY_SYS_SETTING, sysSettingConstant);
           if(set){
               log.info("初始化配置已上传到redis中...");
           }
       }catch (Exception e){
           log.error("初始化配置上传到redis中失败...", e);
       }
    }

    /**
     * 程序销毁后之前做的操作
     */
    @PreDestroy
    public void cleanup(){
        log.info("--------程序销毁前操作--------");
        try{
            TokenUserInfoDto tokenUserInfoDto = CommonUtil.getSecurityContext();
        }catch (Exception e){
            log.error("无法获取SpringSecurity");
        }
        //        Boolean aBoolean = redisComponent.removeUserHeartbeat();
//        if(!aBoolean){
//            log.error("--------心跳无法销毁--------");
//            throw new RuntimeException("心跳无法移除");
//        }
//        log.info("--------心跳已经销毁--------");
        Boolean del = (Boolean) redisUtil.del(CodeConstant.REDIS_KEY_SYS_SETTING);
        if(!del){
            log.error("--------基础配置无法销毁--------");
            throw new RuntimeException("基础配置无法销毁");
        }
        log.info("--------基础配置已经销毁--------");

    }
}
